package com.huawei.petapp2.search;

import android.content.Context;
import android.content.Intent;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.huawei.petapp2.R;
import com.huawei.petapp2.activity.GoodDatailActivity;
import com.huawei.petapp2.activity.widget.BaseActivity;
import com.huawei.petapp2.activity.widget.SimpleSearchView;
import com.huawei.petapp2.activity.widget.loadmore.LoadMoreFooter;
import com.huawei.petapp2.activity.widget.wrapper.PtrWrapper;
import com.huawei.petapp2.activity.widget.wrapper.ToolbarWrapper;
import com.huawei.petapp2.constant.HttpUrl;
import com.huawei.petapp2.entity.Result;
import com.huawei.petapp2.entity.SearchBean;
import com.huawei.petapp2.network.core.ResponseEntity;
import com.huawei.petapp2.network.entity.Filter;
import com.huawei.petapp2.network.entity.Pagination;
import com.huawei.petapp2.utils.DateUtil;
import com.huawei.petapp2.utils.PreferenceHelper;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;
import butterknife.OnItemClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 搜索商品页面.
 */
public class SearchGoodsActivity extends BaseActivity {

    private static final String EXTRA_SEARCH_FILTER = "EXTRA_SEARCH_FILTER";
    int userid= PreferenceHelper.getInt("userId", Objects.requireNonNull(getContext()));
    String token=PreferenceHelper.getString("token",Objects.requireNonNull(getContext()));
    final private static Gson gson=new GsonBuilder().serializeNulls().create();
    public static Intent getStartIntent(Context context, int cid) {

        Intent intent = new Intent(context, SearchGoodsActivity.class);
        intent.putExtra(EXTRA_SEARCH_FILTER, String.valueOf(cid));
        return intent;
    }

    @BindView(R.id.search_view)
    SimpleSearchView mSearchView;
    @BindView(R.id.list_goods)
    ListView goodsListView;
    @BindViews({R.id.text_is_hot, R.id.text_most_expensive, R.id.text_cheapest})
    List<TextView> tvOrderList;

    private Filter mFilter;
    private final Pagination mPagination = new Pagination();
    private boolean mHasMore;
    private SearchGoodsAdapter mGoodsAdapter;
    private LoadMoreFooter mFooter;
    private PtrWrapper mPtrWrapper;
    private Call mSearchCall;
    String cid;
    List<SearchBean> goodsList;

    protected int getContentViewLayout() {
        return R.layout.activity_search_goods;
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_search_goods;
    }

    @Override
    public void initView() {
        //设置标题
        new ToolbarWrapper(this);
        tvOrderList.get(0).setActivated(true);
        cid= getIntent().getStringExtra(EXTRA_SEARCH_FILTER);

        /*String filterStr = getIntent().getStringExtra(EXTRA_SEARCH_FILTER);
        mFilter = new Gson().fromJson(filterStr, Filter.class);*/
        OkHttpClient client = new OkHttpClient();
        Request request1 = new Request.Builder()//获取改用户全部地址
                .url(HttpUrl.getBaseUrl()+"/product/listbycid"+"/"+cid)
                .addHeader("Token",token)
                .build();

        client.newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                    String results = response.body().string();
                    Result result=gson.fromJson(results,Result.class);
                    goodsList= DateUtil.getList9(result);
                }
            }
        });
        mPtrWrapper = new PtrWrapper(this) {
            @Override
            public void onRefresh() {
                OkHttpClient client = new OkHttpClient();
                Request request1 = new Request.Builder()//获取改用户全部地址
                        .url(HttpUrl.getBaseUrl()+"/product/listbycid"+"/"+cid)
                        .addHeader("Token",token)
                        .build();

                client.newCall(request1).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println(e.getMessage());
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(response.code() >= 200 && response.code() < 300) {
                            String results = response.body().string();
                            Result result=gson.fromJson(results,Result.class);
                            goodsList= DateUtil.getList9(result);
                        }
                    }
                });

            }
        };
        //搜索商品
        mSearchView.setOnSearchListener(query -> {
            OkHttpClient client2 = new OkHttpClient();
            Request request2 = new Request.Builder()//获取改用户全部地址
                    .url(HttpUrl.getBaseUrl()+"/product"+"/"+query)
                    .addHeader("Token",token)
                    .build();

            client2.newCall(request2).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println(e.getMessage());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if(response.code() >= 200 && response.code() < 300) {
                        String results = response.body().string();
                        Result result=gson.fromJson(results,Result.class);
                        System.out.println("新的搜索商品请求请求请求OnintView"+result);
                        goodsList= DateUtil.getList9(result);
                        System.out.println("新的搜索商品请求请求请求"+result);
                    }
                }
            });
        });
        //商品列表
        mGoodsAdapter = new SearchGoodsAdapter(getContext());
        goodsListView.setAdapter(mGoodsAdapter);
        mFooter = new LoadMoreFooter(this);
       // goodsListView.addFooterView(mFooter);
        /*goodsListView.setOnScrollListener(new EndlessScrollListener(0, 1) {
            @Override
            public boolean onLoadMore(int page, int totalItemsCount) {
                if (mHasMore && mSearchCall == null) {
                    mFooter.setState(LoadMoreFooter.STATE_LOADING);
                    searchGoods(false);
                    return true;
                }
                return false;
            }
        });*/

        //刷新
        mPtrWrapper.postRefresh(50);
    }

    @Override
    public void initData() {
        System.out.println("获取的商品分类id"+cid);
        OkHttpClient client = new OkHttpClient();
        Request request1 = new Request.Builder()//获取改用户全部地址
                .url(HttpUrl.getBaseUrl()+"/product/listbycid"+"/"+cid)
                .addHeader("Token",token)
                .build();

        client.newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                    String results = response.body().string();
                    Result result=gson.fromJson(results,Result.class);
                    System.out.println("新的商品列表请求OnintView"+result+"\n");
                    goodsList= DateUtil.getList9(result);
                    mGoodsAdapter.reset(goodsList);

                }
            }
        });
        System.out.println("新的商品列表请求"+goodsList);

    }

    @Override
    public void initEvent() {

    }

    @Override
    protected void onBusinessResponse(String apiPath, boolean success, ResponseEntity rsp) {
       /* if (!ApiPath.SEARCH.equals(apiPath)) {
            throw new UnsupportedOperationException(apiPath);
        }
        //停止刷新
        mPtrWrapper.stopRefresh();
        if (success) {
            ApiSearch.Rsp searchRsp = (ApiSearch.Rsp) rsp;
            Paginated paginated = searchRsp.getPaginated();
            if (mPagination.getPage() * paginated.getCount() > paginated.getTotal()) {
                throw new IllegalStateException("Load more data than needed!");
            }
            mHasMore = paginated.hasMore();
            List<SimpleGoods> goodsList = searchRsp.getData();
            //是否还有数据
            if (mHasMore) {
                mFooter.setState(LoadMoreFooter.STATE_LOADED);
            } else {
                mFooter.setState(LoadMoreFooter.STATE_COMPLETE);
            }
            if (mPagination.isFirst()) {
                mGoodsAdapter.reset(goodsList);
            } else {
                mGoodsAdapter.addAll(goodsList);
            }
        }
        mSearchCall = null;*/

    }

    @OnClick({R.id.text_is_hot, R.id.text_most_expensive, R.id.text_cheapest})
    void chooseQueryOrder(TextView textView) {
        if (mSearchCall != null) return;
        if (textView.isActivated()) return;
        for (TextView tv : tvOrderList) {
            tv.setActivated(false);
        }
        textView.setActivated(true);
        String sortBy;
        switch (textView.getId()) {
            case R.id.text_is_hot:
                sortBy = Filter.SORT_IS_HOT;
                break;
            case R.id.text_most_expensive:
                sortBy = Filter.SORT_PRICE_DESC;
                break;
            case R.id.text_cheapest:
                sortBy = Filter.SORT_PRICE_ASC;
                break;
            default:
                throw new UnsupportedOperationException();
        }
        mFilter.setSortBy(sortBy);
        mPtrWrapper.autoRefresh();
    }

    @OnItemClick(R.id.list_goods) void onItemClick(int position) {
        SearchBean searchBean = (SearchBean) goodsListView.getItemAtPosition(position);
        if (searchBean != null) {
            Intent intent = GoodDatailActivity.getStartIntent(this, Integer.parseInt(searchBean.getProductId()));
            startActivity(intent);
        }
    }

    /**
     * 搜索页面
     * @param isRefresh
     */
    private void searchGoods(final boolean isRefresh) {

       /* if (mSearchCall != null) {
            throw new UnsupportedOperationException();
        }
        if (isRefresh) {
            mPagination.reset();
            goodsListView.setSelection(0);
        } else {
            mPagination.next();
        }
        ApiSearch apiSearch = new ApiSearch(mFilter, mPagination);
        mSearchCall = enqueue(apiSearch);*/

    }

}
